/**
 * Created by fangjiehua on 15/8/28.
 */

var crypto = require('crypto');
var request = require('request');
var dateFormat = require('dateformat');

var AccountSid = '0a09b4837b90abd89706621eaa844dec';
var AuthToken = '047852b1a478b2b6dfc9bd0df0620004';
var AppId = '9a5e0acda6064188b260bfadf8e9f11e';

var Host = 'http://imrest.ucpaas.com';
var Softver = '2015-06-30';


function getSig(accountSid, accountToken, timestamp) {
    var sig = accountSid + accountToken + timestamp;
    return crypto.createHash('md5').update(sig).digest('hex').toUpperCase();
}

function getAuth(accountSid,timestamp) {
    var src = new Buffer(accountSid + ":" + timestamp);
    return src.toString('base64');
}


module.exports = function() {

    function ucsrest() {

        this.host = Host;
        this.softver = Softver;
        this.accountSid = AccountSid;
        this.accountToken = AuthToken;
        this.appId = AppId;
    }

    ucsrest.prototype = {
        constructor:ucsrest,
        getUrl: function (path,timestamp) {

            var signature = getSig(this.accountSid, this.accountToken, timestamp);
            var url = "/" + this.softver + "/restApi/" + this.accountSid + "/"+path+"?sig=" + signature;
            return url;
        },
        getOptions : function (path, body) {

            var nowTime = new Date();
            var timestamp = dateFormat(nowTime, 'yyyymmddHHMMss');
            var self = this;
            var url = self.getUrl(path, timestamp);

            console.log('request url:'+url);

            var options = {
                uri: self.host + url,
                headers: {
                    'Authorization': getAuth(self.accountSid, timestamp),
                    'Accept': "application/json",
                    'Content-Type': 'application/json;charset=utf-8'
                },
                json:body
            }

            return options;
        },
        requestApi: function( method,path, param, callback) {

            var self = this;
            var body = param;
            var options = self.getOptions(path, body);

            if (method == 'GET'){

                for (var key in body){

                    options.uri = options.uri+'&'+key+'='+body[key];

                }

                request.get(options, callback);

            }else if(method == 'POST') {
                request.post(options, callback).json(body);
            }
        }
    };

    return ucsrest;
};